import React, { Component } from 'react';
import './Home.scss'
import Header from '../../components/Header/Index'
import Swiper from '../../components/Swiper/Index'
import Nav from '../../components/Nav/Index'
import Seckill from '../../components/Seckill/Index'
import { sleep } from 'antd-mobile/es/utils/sleep'
import service from '../../api/index'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile';


class Home extends Component<any, any> {

    constructor(props: any) {
        super(props);
        this.state = {
            bannerList: [],
            proList: [],
            hasMore: true,
            page: 1,
        }
    }

    async componentDidMount() {
        // 轮播图
        var res = await service.address.bannerList({})
        // 商品数据
        var data = await service.pro.proList({})

        this.setState({
            bannerList: res.data.data,
            proList: data.data.data
        })

    }

    // 去详情页
    toDetail(id: any) {
        // console.log(id);       
        this.props.history.push({ pathname: '/detail', state: { id } })
    }

    loadMore = async () => {
        var res = await service.pro.proList({ count: this.state.page, limitNum: 10 })
        await sleep(2000)
        this.setState({
            proList: [...this.state.proList, ...res.data.data],
            page: this.state.page + 1,
            hasMore: res.data.data.length > 0
        })

    }

    render() {
        return (
            <div className='home'>
                {/* 渲染 Header 组件 */}
                <Header cityId={this.props.location} />

                <PullToRefresh
                    onRefresh={async () => {
                        await sleep(1000)
                    }}
                >
                    {/* 渲染 Swiper 组件 */}
                    <Swiper bannerList={this.state.bannerList} />
                    {/* 渲染 Nav 组件 */}
                    <Nav />
                    {/* 渲染 Seckill 组件 */}
                    <Seckill />

                    <div className="pro">
                        {
                            this.state.proList.map((item: any, index: any) => {
                                return (
                                    // 首页商品列表
                                    <div className="box" key={index} onClick={() => this.toDetail(item.proid)}>
                                        <img src={item.img1} alt="" />
                                        <div className="name">{item.proname}</div>
                                        <div className="price">¥{item.originprice}</div>
                                    </div>
                                )
                            })
                        }
                        <InfiniteScroll loadMore={this.loadMore} hasMore={this.state.hasMore} />

                    </div>

                </PullToRefresh>
            </div>
        );
    }
}

export default Home;